package org.threebitsoftware.tbb.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.log4j.Logger;

import com.pew.util.dao.DatabaseConection;
import com.pew.util.dao.DatabaseUtil;

/*
 * Created: Nov 15, 2009
 * Original Author: Elwin
 * Project:
 * Copyright:
 * 
 * Purpose:
 * Contains helper methods for the database.
 */

/*
 * Copyright (c) 2009, 3BitSoftware
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *   * Neither the name of the <organization> nor the
 *     names of its contributors may be used to endorse or promote products
 *     derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY <copyright holder> ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

public class DaoHelper {
	private static Logger cLogger = Logger.getLogger(DaoHelper.class);
	
	private static final String C_STR_SELECT_MAX = "SELECT MAX(?) FROM ?";
	private static final int C_I_INCREMENT = 1;
	
	/**
	 * Retrieves the next id for an integer field in a table.
	 * @param myTableName ; The table name.
	 * @param myField ; The column.
	 * @param myConnection ; A database connection.
	 * @return The next value in the table; -1 if an error occurs.
	 */
	public static int getNextId(String myTableName, String myField, Connection myConnection)
	{
		int liReturn = -1;
		String lStrStatement = C_STR_SELECT_MAX;
		PreparedStatement lPS = null;
		ResultSet lRS = null;
		
		cLogger.debug("Attempting to get the next ID for: " + myField + " FROM " + myTableName);
		
		lStrStatement = lStrStatement.replaceFirst("[?]", myField);
		lStrStatement = lStrStatement.replaceFirst("[?]", myTableName);
		
		cLogger.debug("Statement: " + lStrStatement);
		
		
		try {
			lPS = myConnection.prepareStatement(lStrStatement);
			
			cLogger.debug("Prepared statement: " + lPS.toString());
			lRS = lPS.executeQuery();
			
			if(lRS.getFetchSize() != 1)
			{
				throw new SQLException("Fetch size was unexpected; should be 1, is " + lRS.getFetchSize());
			}
			else
			{
				lRS.next();
				liReturn = lRS.getInt(1);
				cLogger.debug("Found the current id to be" + liReturn + " for " + myField + " @ " + myTableName);
				liReturn += C_I_INCREMENT;
				cLogger.debug("Set return to: " + liReturn);
			}
		}
		catch (SQLException sqlex)
		{
			cLogger.error("An exception occured while trying to get a next id.");
			cLogger.error(sqlex.getMessage(), sqlex);
		}
		finally
		{
			cLogger.debug("Attempting to close connections.");
			
			try {
				if(lRS != null)
				{
					lRS.close();
				}
				
				if(lPS != null)
				{
					lPS.close();
				}
			}
			catch(SQLException sqlex)
			{
				cLogger.error("Couldn't close a db object.", sqlex);
			}
		}
		
		cLogger.info("Returning new id: " + liReturn);
		return liReturn;
	}
	
	public static void createOrUpdate(Object myObjGen, String myClassName)
	{
		
		/*
		
		
		if(myObjGen.getIdPhoneNumber() > -1)
		{
			cLogger.debug("Attempt to Update PhoneNumber: " + myPN.getIdPhoneNumber());
			
			lDAO.update(lPNG, DatabaseConection.getDBConn());
			
			cLogger.info("Done updating phone number.");
		}
		else
		{
			cLogger.debug("New PhoneNumber Detected; id is -1.");
			
			lDAO.create(lPNG, DatabaseConection.getDBConn());
			
			cLogger.info("Created a new phone number");
		}
		*/
	}
	
	public static Connection getDBConnection() {
		return DatabaseConection.getDBConn();
	}

}
